const router = require('koa-router')()
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.prefix('/comments')

router.post('/:imageid', async ctx => {
  const image = await Image.findById(ctx.params.imageid)
  const {email, nickname, comment} = ctx.request.body
  const comments = await Comment.find({})

  if(image) {
    await Comment.create({
      email, nickname, comment, image: image._id, imagediskname: image.diskfilename
    })
    ctx.redirect(`/images/${ctx.params.imageid}`)
  }
})

module.exports = router